package com.health.validator;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import murphy.validator.FieldDesc;
import murphy.validator.Validator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.health.exceptions.ValidatorException;
import com.health.exceptions.ValidatorLevelException;
import com.health.model.User;

/**
 * @author DirkMurphy
 * 
 * @blog http://www.cnblogs.com/dirkmurphyjava/
 * 
 * @date
 * 
 * @introduction
 */
public class UserValidator extends Validator
{
	protected List<FieldDesc>	fieldList;

	private Log					log	= LogFactory.getLog(UserValidator.class);

	public UserValidator()
	{

		System.out.println("---------------------------userValidator initialed");
	}

	@Override
	public String validate(Object obj) throws ValidatorLevelException
	{
		log.info("------------------------------------------UserValidator working");
		User user = (User) obj;

		String result = "";
		List<FieldDesc> list = this.getFieldList();
		for (int i = 0; i < list.size(); i++)
		{
			FieldDesc desc = list.get(i);
			String fieldName = desc.getName();
			String fieldType = desc.getType();
			Object fieldValue = "";
			StringBuffer sb = new StringBuffer("get");
			String start = fieldName.substring(0, 1);
			String startUp = start.toUpperCase();
			String end = fieldName.substring(1);
			fieldName = startUp.concat(end);
			sb.append(fieldName);
			Method meth;
			try
			{
				meth = user.getClass().getMethod(sb.toString(), null);
				fieldValue = meth.invoke(user, null);
			}
			catch (SecurityException e)
			{
				log.error(e);
				throw new ValidatorLevelException(e.getMessage(), e);
			}
			catch (NoSuchMethodException e)
			{
				log.error(e);
				throw new ValidatorLevelException(e.getMessage(), e);
			}
			catch (IllegalArgumentException e)
			{
				log.error(e);
				throw new ValidatorLevelException(e.getMessage(), e);
			}
			catch (IllegalAccessException e)
			{
				log.error(e);
				throw new ValidatorLevelException(e.getMessage(), e);
			}
			catch (InvocationTargetException e)
			{
				log.error(e);
				throw new ValidatorLevelException(e.getMessage(), e);
			}
			result = this.fieldValidate(desc, fieldName, fieldValue);
			if (result.length() > 0)
			{
				return result;
			}
		}
		return null;
	}

	/**
	 * getters and setters
	 * */
	public List<FieldDesc> getFieldList()
	{
		return fieldList;
	}

	public void setFieldList(List<FieldDesc> fieldList)
	{
		this.fieldList = fieldList;
	}

}
